package com.gather.core;

import org.apache.log4j.Logger;

import com.common.cache.Cache;
import com.common.constant.SnatchConstant;
import com.common.dto.SnatchItem;
import com.common.dto.SnatchTask;
import com.common.dto.SnatchVersion;
import com.common.utils.CacheUtil;
import com.gather.system.AccountData;
import com.work.service.SnatchControl;
import com.work.service.SnatchService;
import com.work.vo.SnatchData;
import com.work.vo.ThirdInfo;

public class SnatchThread extends Thread {

	protected Logger logger = Logger.getLogger(SnatchThread.class);
	
	private Cache cache;

	private SnatchTask snatchTask;
	
	private SnatchItem snatchItem;
	
	private boolean flag = true;// 抓取线程运行和销毁的信号量
	
	private long ASSISTA_SLEEP=10*1000;
	
	private SnatchService hgSnatchDataImpl;
	
	@Override
	public void run() {
		while (flag) {
			try {
				Thread.sleep(getsleepTime());
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			ThirdInfo thirdInfo = null;
			try {
				long time = System.currentTimeMillis();
				// logger.info("获取帐号开始!");
				thirdInfo = AccountData.findThirdInfo(snatchTask
						.getWebCode());
				if (thirdInfo != null && flag) {
					thirdInfo.setSnatch(true);
					Long version = findVersion();
					if(null == version){
						logger.info("采集项："+snatchTask+"未取版本号,本次采集跳过！");
						snatchItem.setDescribe("未取版本号,本次采集跳过！");
						continue;
					}
					snatchTask.setStatus(1);
					snatchTask.setStartTime(System.currentTimeMillis());
					snatchTask.setVersion(version);	//获取版本号
					snatchItem.setDescribe("开始采集帐号："+thirdInfo.getLoginAccount().getUserName());
					SnatchData snatchData = hgSnatchDataImpl.getData(
							snatchTask, thirdInfo);
					int status = hgSnatchDataImpl.inspData(snatchData);
					if(SnatchConstant.INSP_FAIL_DTAT_NULL == status){
						snatchItem.setDescribe("采集数据为空，帐号为:"+thirdInfo.getLoginAccount().getUserName());
						AccountData.logBack(thirdInfo);
						continue;
					}else if(SnatchConstant.INSP_FAIL_ACCOUNT_OUTLOGIN == status){
						snatchItem.setDescribe("帐号被登出:"+thirdInfo.getLoginAccount().getUserName());
						AccountData.logBack(thirdInfo);
						continue;
					}else if(SnatchConstant.INSP_FAIL_THIRD_MAINTEN == status){
						snatchItem.setDescribe("内页正在维护中。。。");
						snatchTask.setPage(1);
						snatchTask.setStatus(-1);
						continue;
					}else if(SnatchConstant.INSP_FAIL_SNATCH_TIME == status){
						snatchItem.setDescribe("采集发现第三方时间不正确,智能判断为旧数据,忽略此次采集数据。");
						continue;
					}
					//帐号使用完，重置状态等待其它系统使用
					if (thirdInfo != null) {
						thirdInfo.setSnatch(false);
						thirdInfo = null;
					}
					if (flag) {
						SnatchVersion snatchVersion = findSnatchVersion(snatchData);
						snatchVersion.setSnatchTime(System.currentTimeMillis() - time);
						for(int i=0;i<snatchData.getDatas().length;i++){
							String datastr = snatchData.getDatas()[i];
							if(datastr != null){
								String valuekey = CacheUtil.getSnatchDataKey(snatchTask.getOnlyCode(),snatchTask.getTaskCode(),i);
								cache.set(valuekey, datastr);
							}
						}
						snatchVersion.setVersion(snatchVersion.getVersion()+1);
						String versionkey = CacheUtil.getSnatchTactKey(snatchTask.getOnlyCode(),snatchTask.getTaskCode());
						cache.set(versionkey, snatchVersion);
					}
				}
				// logger.info(nodeTaskInput.getTaskCode()+" 版本号： "+ratioDataInput.getVersion()+" 采集总结束："+(System.currentTimeMillis()-time));
			} catch (Exception e) {
				logger.error("采集任务错误", e);
				snatchItem.setDescribe("采集报错！");
			} finally {
				if (thirdInfo != null) {
					thirdInfo.setSnatch(false);
				}
			}
		}
		logger.info("采集任务结束" + snatchTask);

	}
	
	
	public Long getsleepTime(){
		boolean addtime = false;
		if(snatchTask.getStatus() !=1){
			addtime = true;
		}
		if(addtime)
			return snatchTask.getSleepTiem()+ASSISTA_SLEEP;
		return snatchTask.getSleepTiem();
	}
	
	public void init(SnatchTask snatchTask,SnatchItem snatchItem,Cache cache){
		this.snatchTask = snatchTask;
		this.snatchItem = snatchItem;
		this.cache = cache;
		hgSnatchDataImpl = SnatchControl.getSnatchService(snatchTask.getWebCode());
	}
	
	public void destroy(){
		flag = false;
	}
	
	
	/**
	 * 根据采集数据获取版本号
	 * @param snatchData
	 * @return
	 */
	private SnatchVersion findSnatchVersion(SnatchData snatchData){
		SnatchVersion snatchVersion = new SnatchVersion();
		if(null == snatchData){
			snatchVersion.setVersion(0L);
		}else{
			snatchVersion.setVersion(snatchData.getSnatchTask().getVersion());
			snatchVersion.setSnatchTime(System.currentTimeMillis()-snatchData.getSnatchTask().getStartTime());
			snatchVersion.setThirdTime(snatchData.getSnatchTask().getThirdTime());
			snatchVersion.setThirdPage(snatchData.getSnatchTask().getPage());
			snatchVersion.setDataSize(snatchData.getDatas().length);
		}
		
		return snatchVersion;
	}
	
	/**
	 * 获取当前版本号
	 * @return
	 */
	private Long findVersion(){
		String vkey = CacheUtil.getVersionKey(snatchTask.getItemOnlyCode());
		Long verion = (Long)cache.get(vkey);
		if(null == verion){
			if(!cache.exists(vkey)){
				cache.set(vkey, 0L);
				return 0L;
			}else{
				return null;
			}
		}else{
			return verion;
		}
	}

}
